package com.example.func.service.impl;

import com.example.func.config.GitConfig;
import com.example.func.dto.request.CreateBranchWithRepoRequest;
import com.example.func.dto.request.MergeBranchRequest;
import com.example.func.dto.request.RollbackRequest;
import com.example.func.dto.response.BranchInfo;
import com.example.func.dto.response.MergeResult;
import com.example.func.service.GitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 使用原始 Git 命令的 Git 操作服务实现
 */
@Slf4j
@Service
public class GitCommandServiceImpl implements GitService {

    private static final String REPO_PATH = System.getProperty("user.dir");

    @Autowired
    private GitConfig gitConfig;

    @Override
    public BranchInfo createBranchWithRepo(CreateBranchWithRepoRequest request) {
        try {
            // 1. 确保远程地址配置正确
            ensureRemoteUrl();
            
            // 2. 获取远程分支信息
            fetchRemoteBranches();
            
            // 3. 基于远程分支创建新分支
            String baseBranch = request.getBaseBranch() != null ? request.getBaseBranch() : "master";
            createBranchFromRemote(request.getBranchName(), baseBranch);
            
            BranchInfo info = new BranchInfo();
            info.setName(request.getBranchName());
            info.setType("local");
            info.setIsCurrent(false);
            
            // 4. 推送到远程
            if (request.getPushToRemote() != null && request.getPushToRemote()) {
                pushBranchToRemote(request.getBranchName());
                log.info("分支已推送到远程: {}", request.getBranchName());
            }
            
            log.info("创建分支成功: {}", request.getBranchName());
            return info;
            
        } catch (Exception e) {
            log.error("创建分支失败", e);
            throw new RuntimeException("创建分支失败: " + e.getMessage());
        }
    }

    /**
     * 确保远程地址配置正确
     */
    private void ensureRemoteUrl() throws Exception {
        try {
            // 尝试添加远程地址
            executeGitCommand("remote", "add", "origin", gitConfig.getRemoteUrl());
            log.info("添加远程地址: {}", gitConfig.getRemoteUrl());
        } catch (Exception e) {
            // 远程地址可能已存在，尝试更新
            try {
                executeGitCommand("remote", "set-url", "origin", gitConfig.getRemoteUrl());
                log.info("更新远程地址: {}", gitConfig.getRemoteUrl());
            } catch (Exception ex) {
                log.warn("远程地址配置失败，使用现有配置: {}", ex.getMessage());
            }
        }
    }

    /**
     * 获取远程分支信息
     */
    private void fetchRemoteBranches() throws Exception {
        // 设置凭据并获取远程分支
        String[] env = {
            "GIT_ASKPASS=echo",
            "GIT_USERNAME=" + gitConfig.getUsername(),
            "GIT_PASSWORD=" + gitConfig.getPassword()
        };
        
        executeGitCommandWithEnv(env, "fetch", "origin");
        log.info("获取远程分支信息成功");
    }

    /**
     * 基于远程分支创建新分支
     */
    private void createBranchFromRemote(String branchName, String baseBranch) throws Exception {
        // git branch <branchName> origin/<baseBranch>
        executeGitCommand("branch", branchName, "origin/" + baseBranch);
        log.info("创建分支成功: {} 基于 origin/{}", branchName, baseBranch);
    }

    /**
     * 推送分支到远程
     */
    private void pushBranchToRemote(String branchName) throws Exception {
        // git push -u origin <branchName>
        executeGitCommand("push", "-u", "origin", branchName);
        log.info("推送分支成功: {}", branchName);
    }

    /**
     * 执行 Git 命令
     */
    private String executeGitCommand(String... args) throws Exception {
        return executeGitCommandWithEnv(null, args);
    }

    /**
     * 执行带环境变量的 Git 命令
     */
    private String executeGitCommandWithEnv(String[] env, String... args) throws Exception {
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.directory(new File(REPO_PATH));
        
        // 构建命令
        List<String> command = new ArrayList<>();
        command.add("git");
        for (String arg : args) {
            command.add(arg);
        }
        processBuilder.command(command);
        
        // 设置环境变量
        if (env != null) {
            processBuilder.environment().put("GIT_ASKPASS", "echo");
            processBuilder.environment().put("GIT_USERNAME", gitConfig.getUsername());
            processBuilder.environment().put("GIT_PASSWORD", gitConfig.getPassword());
        }
        
        log.debug("执行命令: {}", String.join(" ", command));
        
        Process process = processBuilder.start();
        
        // 读取输出
        StringBuilder output = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
        }
        
        // 读取错误输出
        StringBuilder error = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                error.append(line).append("\n");
            }
        }
        
        int exitCode = process.waitFor();
        
        if (exitCode != 0) {
            throw new RuntimeException("Git 命令执行失败: " + error.toString());
        }
        
        return output.toString();
    }

    // 其他方法暂时返回空实现，可以根据需要添加
    @Override
    public List<BranchInfo> listBranches() {
        // TODO: 实现分支列表功能
        return new ArrayList<>();
    }

    @Override
    public void checkoutBranch(String branchName) {
        // TODO: 实现分支切换功能
    }

    @Override
    public MergeResult mergeBranch(MergeBranchRequest request) {
        return null;
    }

    @Override
    public List<String> detectConflicts(String sourceBranch, String targetBranch) {
        return Collections.emptyList();
    }

    @Override
    public void rollback(RollbackRequest request) {

    }

    @Override
    public String pullBranchAndCreateTestFile(String branchName) {
        // TODO: 如果需要使用命令行方式实现，可以在这里添加
        throw new UnsupportedOperationException("此方法需要使用 JGit 实现，请使用 GitServiceImpl");
    }

}